<template>
  <div class="reply-wraper">
    <!-- <Toast v-if="sendloading" :message="$lang.sending"></Toast> -->
    <van-cell class="replyRow">
      <div class="inputBox text-overflow" @click="showReplyPopup">
        <img class="shareIcon" src="@/assets/oppo/home/share.svg" alt="" />
        <span class="replyspan" v-html='replyMessage.length ?  "<span style=\"color:#F54636;font-weight: 400; letter-spacing: 2px;padding-right: 1px;\">["+ $lang.drafts_another + "]</span>" +replyMessage : $lang.reply + "..."'></span>
      </div>
      <div class="transmit-move" @click="withAttach">
        <img
          class="transmitIcon"
          src="@/assets/oppo/home/transmit.svg"
          alt=""
        />
        <span>{{ $lang.forward }}</span>
      </div>
      <div class="transmit-move" @click="moveMail">
        <img src="@/assets/oppo/home/replyMove.svg" alt="" />
        <span>{{ $lang.move }}</span>
      </div>
    </van-cell>
    <van-popup v-model="showReply" position="bottom" class="replyPopop">
      <van-cell class="replyTitle" center border>
        <van-dropdown-menu class="dropdown-bar" active-color="#00C00E">
          <div class="replyChoose">
            <span @click="showReplyObject" class="replyObject">{{
              replychoose.text
            }}</span>
            <van-popup
              v-model="showObject"
              position="bottom"
              style="border-radius: 12px 12px 0 0; height: 212px"
            >
              <van-cell border>
                <span class="title">{{ $lang.chooseReplyer }}</span>
              </van-cell>
              <van-cell
                v-for="(item, index) in replayChoose"
                border
                @click="chooseReplyObject(item)"
                :key="index"
                style="height: 52px; padding-top: 0; padding-bottom: 0"
              >
                <span class="object">
                  <p class="replayText">{{ item.text }}</p>
                  <p
                    class="replayPeople text-overflow"
                    v-text="replayList(index)"
                  ></p>
                </span>
              </van-cell>
              <div style="width: 100%; height: 8px; background: #f2f3f5"></div>
              <van-cell border style="height: 52px">
                <span class="object" @click="showObject = false">{{
                  $lang.cancel
                }}</span>
              </van-cell>
            </van-popup>
          </div>
          <img
            class="arrow-icon"
            :src="require('@/assets/oppo/home/arrow-expansion.svg')"
          />
          <p class="objectTitle text-overflow">
            {{ replyersText }}
          </p>

          <img
            src="@/assets/oppo/home/inputLager.svg"
            alt=""
            class="inputLager"
            @click="goToReply(replyMessage)"
          />
        </van-dropdown-menu>
      </van-cell>
      <van-cell class="repltInput" border>
        <textarea
          class="textarea"
          type="text"
          @focus="closeUsual"
          v-model="replyMessage"
          ref="repltInput"
          :placeholder="`${$lang.reply}...`"
        ></textarea>
        <img :src="keyboard" class="openKeyboard" @click="openKeyboards" />

        <van-button
          v-if="replyMessage.length == 0"
          disabled
          type="primary"
          class="sendButton1"
          >{{ $lang.send }}</van-button
        >
        <van-button
          v-else
          type="primary"
          class="sendButton"
          @click="quickReply"
          >{{ $lang.send }}</van-button
        >
      </van-cell>
      <div
        style="max-height: 156px"
        ref="usualReply"
        :style="{ 'overflow-y': usualScroll }"
      >
        <div
          v-for="(item, index) in usualList"
          class="usualReply"
          v-show="!openkeyboard"
          :key="index"
        >
          <div class="reply-tip text-overflow" @click="addUsually(item.tip)">
            {{ item.tip }}
          </div>
          <img
            src="@/assets/oppo/home/del-addusual.svg"
            @click="delUsually(item.id)"
          />
        </div>
      </div>
      <van-cell
        class="addUsualReply"
        @click="showAddUsualReply"
        v-show="!openkeyboard"
      >
        <img src="@/assets/oppo/home/reply.svg" />
        <span>{{ $lang.addCommonExpression }}</span>
      </van-cell>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import Toast from "@/plugins/Toast/Toast";
export default {
  props: {
    mailDetail: {
      type: Object,
    },
  },
  components: {
    Toast,
  },
  created() {
    const { mail, username } = this.userInfo;
    this.selfInfo["address"] = mail;
    this.selfInfo["name"] = username;
    window.qing.on("appear", function () {
      console.warn("页面进入前台");
      // that.getMailDetail;
    });
  },
  data() {
    return {
      showReply: false,
      replychoose: { text: this.$lang.reply, value: false },
      replayChoose: [
        { text: this.$lang.replyAll, value: true },
        { text: this.$lang.reply, value: false },
      ],
      usualList: [],
      keyboard: require("@/assets/oppo/home/keyboard.svg"),
      openkeyboard: false,
      showObject: false,
      replyMessage: "",
      replayObjectList: [],
      usualScroll: "",
      sendloading: false,
      selfInfo: {
        address: "",
        name: "",
        photo: null,
      },
    };
  },
  mounted() {
    this.getUsualList();
    this.objectTitle();
    this.showReply = this.$store.state.newShowReply;
  },
  watch: {
    showReply(newValue) {
      this.$store.commit("changeShowReply", newValue);
      this.objectTitle();

      if (newValue) {
        document
          .getElementById("view")
          .setAttribute(
            "content",
            "user-scalable=0, width = device-width, initial-scale = 1.0"
          );
      } else {
        document
          .getElementById("view")
          .setAttribute(
            "content",
            "user-scalable=yes, width = device-width, initial-scale = 1.0"
          );
      }
    },
    "$route.query.index": {
      handler() {
        this.replychoose = { text: this.$lang.reply, value: false };
      },
      immediate: true,
    },
  },

  computed: {
    ...mapGetters(["newShowReply", "userInfo"]),
    replyersText() {
      if (this.replychoose.value) {
        return this.replayObjectList
          .map((item) => item.name || item.address || "")
          .join(", ");
      }
      return (
        this.mailDetail?.sender?.name || this.mailDetail?.sender?.address || "-"
      );
    },
  },
  methods: {
    ...mapMutations(["SAVECREATEREPLYDETAIL"]),
    moveMail() {
      this.$router.push(`/folderManage/${this.$route.params.id}`);
    },
    replayList(index) {
      if (index == 1) {
        return (
          this.mailDetail?.sender?.name ||
          this.mailDetail?.sender?.address ||
          "-"
        );
      } else {
        const _r = this.replayObjectList;
        let arr = [];
        for (let i = 0; i < _r.length; i++) {
          if (_r[i].name) {
            arr.push(_r[i].name);
          }
        }
        return arr.join(",");
      }
    },
    //回复对象标题
    objectTitle() {
      let TitleList = [];
      TitleList = this.mailDetail.ccRecipients.concat(this.mailDetail.sender);
      const toRecipientsExcludeSelf = this.mailDetail.toRecipients.filter(
        (item) => item.address !== this.selfInfo.address
      );
      TitleList = TitleList.concat(toRecipientsExcludeSelf);
      const res = new Map();
      this.replayObjectList = TitleList.filter(
        (a) => !res.has(a.address) && res.set(a.address, a)
      );
      console.warn("TitleList", TitleList);
      console.warn("replayObjectList", this.replayObjectList);
    },
    // 展示回复对象
    showReplyObject() {
      this.showObject = true;
    },
    // 选择回复对象
    chooseReplyObject(item) {
      this.objectTitle();
      this.replychoose = {};
      this.replychoose = item;
      this.showObject = false;
    },
    closeUsual() {
      this.openkeyboard = true;
      this.keyboard = require("@/assets/oppo/home/openKeyboard.svg");

      const el = this.$refs.repltInput;
      console.warn("scrollIntoView", el.scrollIntoView);

      window.setTimeout(() => {
        el.scrollIntoView(); // 多数手机
        document.body.scrollTop = document.body.scrollHeight; // iOS部分手机
      }, 300);
    },
    // 键盘图标切换
    openKeyboards() {
      let keyboard = this.$refs.repltInput;
      if (!this.openkeyboard) {
        this.keyboard = require("@/assets/oppo/home/openKeyboard.svg");
        this.openkeyboard = true;
        this.$nextTick(() => {
          keyboard.focus();
        });
      } else {
        this.keyboard = require("@/assets/oppo/home/keyboard.svg");
        this.openkeyboard = false;
        this.$nextTick(() => {
          keyboard.blur();
        });
      }
    },
    // 获取常用语
    async getUsualList() {
      this.usualList = [];
      const res = await this.Api.getQuickReply();
      const { success } = res?.data;
      if (success) {
        const { data } = res?.data;
        data.map((item) => {
          this.usualList.push(item);
        });
      }

      if (this.usualList.length > 3) {
        this.usualScroll = "scroll";
      } else {
        this.usualScroll = "";
      }
    },
    // 显示快速回复
    showReplyPopup() {
      this.$store.commit("changeShowReply", true);
      this.showReply = this.newShowReply;
      this.openkeyboard = !this.showReply;
      if (!this.openkeyboard) {
        this.keyboard = require("@/assets/oppo/home/keyboard.svg");
      }
    },
    // 跳转添加常用语界面
    showAddUsualReply() {
      if (this.usualList.length < 5) {
        let mailId = this.$route.params.id;
        this.$router.push({
          path: `/addUsual/${mailId}`,
          query: {
            index: this.$route?.query?.index,
          },
        });
      } else {
        this.$toast.fail(this.$lang.replyWarn);
      }
    },
    // 将常用语加到输入框内
    addUsually(item) {
      this.replyMessage = item;
    },
    //删除常用语
    async delUsually(id) {
      const res = await this.Api.delQuickReplyUsual(id);
      const { success } = res?.data;
      if (success) {
        this.getUsualList();
        this.$toast.clear()
      }
    },
    // 快速回复
    async quickReply() {
      this.sendloading = true;
      try {
        if (this.replyMessage) {
          let requsetBody = {
            comment: this.replyMessage,
            id: this.$route.params.id,
            replyAll: this.replychoose.value,
            replyRecipients: [],
          };
          if (this.replychoose.value) {
            //回复
            requsetBody.replyRecipients = [...this.replayObjectList];
          } else {
            //回复全部
            requsetBody.replyRecipients.push(this.mailDetail.sender);
          }
          const res = await this.Api.quickReply(requsetBody);
          const { success, error } = res?.data;
          if (success) {
            this.$imbedapi(666001002, "sendMail").then((res) =>
              console.warn(res, "邮件发送")
            );
            this.$toast.success(this.$lang.sentSuccess);
          } else {
            this.$toast.fail(error);
          }
          this.sendloading = false;
          this.replyMessage = "";
          this.$store.commit("changeShowReply", false);
          this.showReply = this.newShowReply;
          this.openKeyboard = this.newShowReply;
        }
      } catch (error) {
        this.sendloading = false;
        console.warn("errorrr", error);
        if (error?.data?.error === "不支持对该邮件进行此操作") {
          this.$toast.fail(this.$lang.NotSupport);
        } else {
          this.$toast.fail(this.$lang.Retry);
        }
        console.error("快速回复失败");
      }
    },
    // 全屏回复
    async goToReply(content) {
      let messageid = this.$route.params.id;

      try {
        //因为微软的某些退信不支持回复操作，先用createReply接口试探是否可以回复，
        //若可以，将返回数据保存到vuex中，然后再跳转页面
        const res = await this.Api.createReply(messageid);
        const { success, error, data } = res?.data;
        if (!success && error === "不支持对该邮件进行此操作") {
          this.$toast.fail(this.$lang.NotSupport);
          return;
        } else {
          if (this.replychoose.text === this.$lang.reply) {
            data.contentDrafts = content;
            this.SAVECREATEREPLYDETAIL(data);
            // this.openWebView(`writemail/${messageid}`, {
            //   writeType: "reply",
            // });
          } else if (this.replychoose.text === this.$lang.replyAll) {
            let replyAllDetail = { ...data };
            const map = new Map();
            let toArr = [];
            const toRecipientsExcludeSelf = this.mailDetail.toRecipients.filter(
              (item) => item.address !== this.selfInfo.address
            );
            // console.warn('toRecipientsExcludeSelf',toRecipientsExcludeSelf)
            toArr = toRecipientsExcludeSelf.concat(this.mailDetail.sender);
            toArr = toArr.filter(
              (a) => !map.has(a.address) && map.set(a.address, a)
            );

            replyAllDetail["toRecipients"] = [...toArr];
            replyAllDetail["ccRecipients"] = this.mailDetail.ccRecipients;
            replyAllDetail.contentDrafts = content;
            this.SAVECREATEREPLYDETAIL(replyAllDetail);
            // this.openWebView(`writemail/${messageid}`, {
            //   writeType: "reply",
            // });
          }

          this.$router.replace({
            path: `/writemail/${messageid}`,
            query: {
              writeType: "reply",
              index: this.$route?.query?.index,
            },
          });
        }
      } catch(e) {
        if(e != 600){
          this.$toast.fail(this.$lang.NotSupport);
        }
        console.error("检查是否可以回复，失败",e);
      }
    },
    async transmit(attachFlag) {
      let messageid = this.$route.params.id;
      try { 
        const res = await this.Api.getQuickReply()
        console.warn(res,"通过调用接口，对网络状态进行降级处理");
        this.$router.replace({
        path: `/writemail/${messageid}`,
        query: {
          writeType: "forward",
          withAttach: attachFlag ? "withAttach" : "withoutAttach",
          index: this.$route?.query?.index,
        },
      });
      }catch(e){
        if(e != 600){
          this.$toast.fail("404")
        }
        console.warn("跳转转发页面报错",e);
      }


      // this.openWebView(`writemail/${messageid}`, {
      //   writeType: "forward",
      //   withAttach: attachFlag ? "withAttach" : "withoutAttach",
      // });
    },

    withAttach() {
      const _this = this;
      if (this.mailDetail.attachments.length == 0) {
        _this.transmit(0);
      } else {
        new this.$ActionSheet({
          options: [
            { name: this.$lang.withAttachment, value: "withAttach" },
            { name: this.$lang.withoutAttachment, value: "withoutAttach" },
          ],
          // cancelText: "取消",
          onSelect: (item) => {
            if (item.value === "withAttach") {
              _this.transmit(1);
            } else if (item.value === "withoutAttach") {
              _this.transmit(0);
            }
            //
          },
        });
      }
    },
    replyMessageClear() {
      this.replyMessage = '';
    }
  },
};
</script>

<style lang="less" scoped>
.reply-wraper {
  height: 50px;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0px;
  background: #ffffff;
  box-shadow: 0 -4px 10px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
  z-index: 2;
  .replayPeople {
    font-size: 12px;
    color: #646566;
    text-align: center;
    line-height: 18px;
    font-weight: 400;
    width: 360px;

    text-align: center;
    padding: 0px 20px;
  }
  .replayText {
    font-family: PingFangSC-Regular;
    font-size: 16px;
    color: #323233;
    text-align: center;
    line-height: 24px;
    font-weight: 400;
  }
  .replyRow {
    .van-cell__value {
      display: flex;
      align-items: center;
      width: 100%;

      .inputBox {
        flex: 1;
        height: 28px;
        padding: 0 10px;
        background: #f2f3f5;
        border-radius: 3px;
        line-height: 28px;
        img {
          width: 21px;
          height: 21px;
          vertical-align: middle;
          pointer-events: none;
          line-height: 28px;
        }
        .vanticon {
          transform: rotateY(180deg);
          font-size: 14px;
          color: #969799;
          margin-left: 17px;
          vertical-align: middle;
        }

        .replyspan {
          margin-left: 7px;
          font-size: 12px;
          color: #969799;
          line-height: 28px;
          height:28px;
          font-weight: 400;
          display: inline-block;
        }
      }

      .transmit-move {
        // display: inline-block;
        height: 28px;
        line-height: 28px;
        min-width: 75px;
        text-align: right;
        padding-left: 16px;

        img {
          width: 21px;
          height: 21px;
          pointer-events: none;
          vertical-align: middle;
        }

        span {
          margin-left: 4px;
          font-size: 14px;
          color: #969799;
          line-height: 20px;
          font-weight: 400;
        }
      }
    }
  }

  .replyPopop {
    width: 100%;

    .replyTitle {
      position: relative;
      width: 100%;
      height: 56px;
      padding: 20px 16px;

      .dropdown-bar {
        display: flex;
        align-items: center;
        width: 100%;

        .replyChoose {
          // min-width: 75px;
          .replyObject {
            font-size: 14px;
            color: #00c00e;
            line-height: 22px;
          }
          .van-cell {
            height: 52px;
            .van-cell__value {
              display: flex;
              justify-content: center;
              align-items: center;

              .title {
                font-size: 14px;
                color: #969799;
                text-align: center;
                line-height: 22px;
                font-weight: 400;
              }

              .object {
                font-size: 16px;
                color: #323233;
                text-align: center;
                line-height: 24px;
                font-weight: 400;
              }
            }
          }
        }
        .arrow-icon {
          width: 16px;
          height: 16px;
          // margin: 0 0 0 4px;
        }

        .inputLager {
          width: 20px;
          height: 20px;
        }
        .objectTitle {
          margin: 0 28px 0 8px;
          flex: 1;
          height: 20px;
          font-size: 14px;
          color: #323233;
          text-align: left;
          line-height: 20px;
          span {
            display: inline-block;
            font-size: 14px;
            color: #323233;
            line-height: 14px;
            font-weight: 400;
          }
        }
      }
    }

    .repltInput {
      min-height: 128px;
      width: 100%;
      padding: 12px 16px;
      position: relative;

      textarea {
        display: inline-block;
        font-size: 14px;
        color: #323233;
        width: 100%;
        height: 60%;
        caret-color: #323233;
      }

      .openKeyboard {
        position: absolute;
        bottom: 0;
        right: 1.9466694318142rem;
        width: 0.6400009090896rem;
        height: 0.6400009090896rem;
      }
      .sendButton1 {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 1.7066690909056rem;
        height: 0.6400009090896rem;
        background: #00c00e;
        opacity: 0.3;
        border-radius: 4px;
        font-size: 0.3200004545448rem;
        color: #ffffff;
        line-height: 0.3200004545448rem;
        font-weight: 400;
      }
      .sendButton {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 1.7066690909056rem;
        height: 0.6400009090896rem;
        background: #00c00e;
        border-radius: 4px;
        font-size: 0.3200004545448rem;
        color: #ffffff;
        line-height: 0.3200004545448rem;
        font-weight: 400;
      }
    }

    .usualReply {
      position: relative;
      height: 52px;
      padding: 19px 16px;
      display: flex;
      align-items: center;
      .reply-tip {
        // width: calc(100% - 20px);
        // display: inline-block;
        flex: 1;
        font-size: 14px;
        color: #646566;
        // line-height: 14px;
        font-weight: 400;
        margin-right: 8px;
      }

      img {
        // position: absolute;
        width: 20px;
        height: 20px;
        // vertical-align: middle;
        min-width: 20px;
      }
    }

    .addUsualReply {
      height: 56px;
      padding: 16px;

      img {
        width: 24px;
        height: 24px;
        vertical-align: middle;
      }

      span {
        font-size: 16px;
        color: #323233;
        text-align: center;
        line-height: 26px;
        font-weight: 400;
        margin-left: 8px;
      }
    }
  }
}
// 样式补充
/deep/ .van-cell::after {
  transform: scale(1.5, 0.5);
}
</style>
